package thesis.prototype;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
//import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private static final int NOTIFICATION_ID = 7;
	
	public static final String MEET_ME_MSG = "MEETME INVITE";
	/*
	 * The SMS that informs the user of a MeetMe invite is in the form:
	 * MEETME INVITE <phone>
	 * where <phone> is the phone number of the meeting organizer.
	 */
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent.getAction().equals(ACTION))
		{
			// Intent is SMS received. Check message
			Bundle bundle = intent.getExtras();
			SmsMessage[] msgs = null;
			String str = "";
			if(bundle!=null)
			{
				Object[] pdus = (Object[])bundle.get("pdus");
				msgs = new SmsMessage[pdus.length];
				for(int i = 0; i < msgs.length; i++)
				{
					msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
					str += msgs[i].getMessageBody().toString();
					str += " " + msgs[i].getOriginatingAddress();
				}
			}
			
			// Check if message is MeetMe invite
			if(str.startsWith(MEET_ME_MSG))
			{
				// Check who invited, get third token for phone number
				String[] tokens = str.split(" ");
				if(tokens.length>3)
				{
					// TODO: some sort of error, just ignore for now?
				}
				String invitedBy = tokens[2];
				// might need to get contact details for notification
				
				NotificationManager notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
				int icon = R.drawable.icon;
				String tickerText = "MeetMe Invitation from " + invitedBy;
				long when = System.currentTimeMillis();
				Notification notification = new Notification(icon, tickerText, when);
		        //notification.defaults |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
		        notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
		        
				String notifyTitle = "MeetMe";
		        String notifiyText  = "You have been invited to a meeting! Open the MeetMe app to transmit your location.";
		        Intent startActivity = new Intent();
		        startActivity.setClass(context, thesis.prototype.Main.class);
		        startActivity.setAction(thesis.prototype.Main.class.getName());
		        PendingIntent startIntent = PendingIntent.getActivity( context, 0, startActivity, 0);
		        
		        notification.setLatestEventInfo(context, notifyTitle, notifiyText, startIntent);
		        notifyManager.notify(NOTIFICATION_ID, notification);
			}
		}
	}

}
